package com.dfbz.demo01_多线程实现聊天案例;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
public class Demo01_Client {


    public static void main(String[] args) throws IOException {


        // 创建一个客户端,去连接服务器
        Socket socket = new Socket("127.0.0.1",9999);

        // 获取与服务器的输入输出流
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();


        // 读线程,专门用于读取服务器的信息
        new Thread(){

            @Override
            public void run() {
                try {
                    byte[] data=new byte[1024];

                    while (true){
                        int len = is.read(data);
                        System.out.println("接收到来自服务器的信息【"+new String(data,0,len)+"】");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        // 写线程,专门向服务器写出数据
        new Thread(){
            @Override
            public void run() {
                try {
                    Scanner scanner = new Scanner(System.in);
                    while (true){
                        String str = scanner.next();
                        os.write(str.getBytes());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

}
